#include "ThreadPool/LogMessage.hpp"

#include <iostream>

#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/types.h>

void usage(const char* args)
{
    std::cout << "usage:\n" << args << " IP port" << std::endl;
    exit(1);
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        usage(argv[0]);
    }

    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // 2. connect和服务器建立连接
    sockaddr_in server; // server 相关字段
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port = htons(atoi(argv[2]));
        // connect建立连接
    if(connect(sockfd, reinterpret_cast<sockaddr*>(&server), sizeof(server)) < 0)
    {
        LogMessage(FATAL, _F, _L, "client connect fail");
        exit(2);
    }

    char buff[1024];
    while(1)
    {
        // 发送数据
        memset(buff, 0, sizeof(buff));
        std::cout << "请输入你要发送的信息::";
        std::cin >> buff;
        if(strcmp(buff, "quit") == 0)
        {
            std::cout << "clinet quit" << std::endl;
            break;
        }
        send(sockfd, buff, strlen(buff), 0);// 阻塞式发送

        // 接收数据
        recv(sockfd, (void*)buff, sizeof(buff), 0);
        std::cout << "server echo #" << buff << std::endl;
    }

    close(sockfd);
    return 0;
}